# -*- coding: UTF-8 -*-
"""
聊天命令 [管理指令]
By AnpyD
"""


# 设置PATH
import bs
import sys
sys.path.append(bs.getEnvironment()['systemScriptsDirectory'] + "/anm")

# 导入模块
import bsInternal
import member
import member_option


class chatOptions(object):
    def __init__(self):
        self.owner_list = ["pb-IF4OVEMSDQ=="]
        self.admin_list = member.AdminList
        self.ban_list = member.autoKickList

    def check_owner(self, clientID):
        is_owner = []
        for i in bsInternal._getForegroundHostActivity().players:
            if i.getInputDevice().getClientID() == clientID:
                is_owner = i.get_account_id()
        if is_owner in self.owner_list:
            return True
        else:
            bs.screenMessage('此命令仅供腐竹使用！', color=(1,0,0), clients=[clientID], transient=True)
            return False

    def check_admin(self, clientID):
        is_admin = []
        for i in bsInternal._getForegroundHostActivity().players:
            if i.getInputDevice().getClientID() == clientID:
                is_admin = i.get_account_id()
        if is_admin in self.admin_list or is_admin in self.owner_list:
            return True
        else:
            bs.screenMessage('此命令仅供管理员使用！', color=(1,0,0), clients=[clientID], transient=True)
            return False

    def getId(self, clientID):
        for i in bsInternal._getForegroundHostActivity().players:
            if i.getInputDevice().getClientID() == clientID:
                ID = i.get_account_id()

        return ID

    def opt(self,clientID,msg):
        m = msg.split(' ')[0]
        a = msg.split(' ', 1)[1:]
        activity = bsInternal._getForegroundHostActivity()
        with bs.Context(activity):
            if m == '#kick':
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 Kick ID 来指定你要提出的人！', color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        try:
                            kickedPlayerID = int(a[0])
                        except Exception:
                            bs.screenMessage('未发现此玩家！', color=(1,0,0), clients=[clientID], transient=True)
                        else:
                            if not kickedPlayerID == -1:
                                bsInternal._disconnectClient(kickedPlayerID)
                            else:
                                bs.screenMessage('你无法将此玩家踢出服务器！', color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#list':
                if self.check_admin(clientID=clientID):
                    bsInternal._chatMessage("==========玩家 Kick ID列表(供kick命令使用)==========")
                    for i in bsInternal._getGameRoster():
                        try:
                            bsInternal._chatMessage(i['players'][0]['nameFull'] + "     kick ID " + str(i['clientID']))
                        except Exception:
                            pass
                    bsInternal._chatMessage("==========玩家ID列表(供其他命令使用)=============")
                    for s in bsInternal._getForegroundHostSession().players:
                        bsInternal._chatMessage(s.getName() +"  ID = "+ str(bsInternal._getForegroundHostSession().players.index(s)))

            elif m == '#admin':
                if self.check_owner(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 玩家ID 来指定新增管理员！', color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        if len(a[0]) > 2:
                            for i in bs.getActivity().players:
                                try:
                                    if (i.getName()).encode('utf-8') == (a[0]):
                                        adminClient = i.getInputDevice().getClientID()
                                        adminName = i.getName().encode('utf-8')
                                        adminPlayerID = i.get_account_id()
                                        admin_list = []
                                        admin_list= member.AdminList
                                        if adminPlayerID not in admin_list:
                                            member_option.add_admin(client_id=adminPlayerID)
                                            bsInternal._chatMessage("成功将 "+str(adminName) + " 加入管理员列表！")
                                            i.removeFromGame()
                                            reload(member)
                                        else:
                                            bs.screenMessage(str(adminName) + " 已经是管理员了！", color=(1,0,0), clients=[clientID], transient=True)
                                except Exception:
                                    pass
                        else:
                            try: 
                                adminClient = bsInternal._getForegroundHostSession().players[int(a[0])]
                            except Exception:
                                bs.screenMessage("未发现此玩家！", color=(1,0,0), clients=[clientID], transient=True)
                            else:
                                admin_list = []
                                admin_list = member.AdminList
                                adminPlayerID = adminClient.get_account_id()
                                if adminPlayerID not in admin_list:
                                    member_option.add_admin(client_id=adminPlayerID)
                                    bsInternal._chatMessage("成功将 "+str(adminClient) + " 加入管理员列表！")
                                    adminClient.removeFromGame()
                                    reload(member)
                                else:
                                    bs.screenMessage(str(adminClient) + " 已经是管理员了！", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#unadmin':
                if self.check_owner(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 玩家ID 来指定要删除的管理员！', color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        if len(a[0]) > 2:
                            for i in bs.getActivity().players:
                                try:
                                    if (i.getName()).encode('utf-8') == (a[0]):
                                        adminClient = i.getInputDevice().getClientID()
                                        adminName = i.getName().encode('utf-8')
                                        adminPlayerID = i.get_account_id()
                                        admin_list = []
                                        admin_list = member.AdminList
                                        if adminPlayerID in admin_list:
                                            member_option.del_admin(client_id=adminPlayerID)
                                            bsInternal._chatMessage("已将 "+str(adminName) + " 从管理员列表中删除！")
                                            reload(member)
                                        else:
                                            bs.screenMessage(str(adminName) + " 不是管理员！", color=(1,0,0), clients=[clientID], transient=True)
                                except Exception:
                                    pass
                        else:
                            try: 
                                adminClient = bsInternal._getForegroundHostSession().players[int(a[0])]
                            except Exception: 
                                bs.screenMessage("未发现此玩家！", color=(1,0,0), clients=[clientID], transient=True)
                            else:
                                admin_list = []
                                admin_list = member.AdminList
                                adminPlayerID = adminClient.get_account_id()
                                if adminPlayerID in admin_list:
                                    member_option.del_admin(client_id=adminPlayerID)
                                    bsInternal._chatMessage("已将 "+str(adminClient) + " 从管理员列表中删除！")
                                    reload(member)
                                else:
                                    bs.screenMessage(str(adminClient) + " 不是管理员！", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#adminid':
                if self.check_owner(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 设备ID 来指定要添加为管理员的玩家！', color=(1,0,0), clients=[clientID], transient=True)
                    else:               
                        if len(a[0]) > 2:
                            adminPlayerID = str(a[0])
                            foolist = []
                            foolist = member.AdminList
                            if adminPlayerID not in foolist:
                                member_option.add_admin(client_id=adminPlayerID)
                                bsInternal._chatMessage("成功将 "+str(adminPlayerID) + " 加入管理员列表！")
                                reload(member)
                            else:
                                bs.screenMessage("玩家 "+str(adminPlayerID) + " 已经是管理员了！", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#unadminid':
                if self.check_owner(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 设备ID 来指定要删除的管理员！', color=(1,0,0), clients=[clientID], transient=True)
                    else:               
                        if len(a[0]) > 2:
                            adminPlayerID = str(a[0])
                            foolist = []
                            foolist = member.AdminList
                            if adminPlayerID in foolist:
                                member_option.del_admin(client_id=adminPlayerID)
                                bsInternal._chatMessage("成功将 "+str(adminPlayerID) + " 从管理员列表中删除！")
                                reload(member)
                            else:
                                bs.screenMessage("玩家 " + str(adminPlayerID) + " 不在管理员列表中！", color=(1,0,0), clients=[clientID], transient=True)
                               
            elif m == '#ban':
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 玩家ID 来指定要封禁的玩家！', color=(1,0,0), clients=[clientID], transient=True)
                    else:               
                        if len(a[0]) > 2: #try nick if nick's lenght is more then 2 else try player id FIX ME !!!
                            for i in bs.getActivity().players:
                                try:
                                    if (i.getName()).encode('utf-8') == (a[0]):
                                        bannedClient = i.getInputDevice().getClientID()
                                        bannedName = i.getName().encode('utf-8')
                                        bannedPlayerID = i.get_account_id()
                                        foolist = []
                                        foolist = member.autoKickList
                                        if bannedPlayerID not in foolist:
                                            member_option.add_ban(client_id=bannedPlayerID)
                                            bsInternal._chatMessage("玩家 "+str(bannedName) + " 已封禁！")
                                            i.removeFromGame()
                                            reload(member)
                                        else:
                                            bs.screenMessage("玩家 "+str(bannedName) + " 已经被封禁了！", color=(1,0,0), clients=[clientID], transient=True)
                                except Exception:
                                    pass
                        else:
                            try: 
                                bannedClient = bsInternal._getForegroundHostSession().players[int(a[0])]
                            except Exception:
                                bs.screenMessage("未发现此玩家", color=(1,0,0), clients=[clientID], transient=True)
                            else:
                                foolist = []
                                foolist = member.autoKickList
                                bannedPlayerID = bannedClient.get_account_id()
                                if bannedPlayerID not in foolist:
                                    member_option.add_ban(client_id=bannedPlayerID)
                                    bsInternal._chatMessage("玩家 " + str(bannedClient) + " 已封禁！")
                                    bannedClient.removeFromGame()
                                    reload(member)
                                else:
                                    bs.screenMessage("玩家 " + str(bannedClient) + " 已经被封禁了！", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#banid':
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 设备ID 来指定要封禁的玩家！', color=(1,0,0), clients=[clientID], transient=True)
                    else:               
                        if len(a[0]) > 2:
                            bannedPlayerID = str(a[0])
                            foolist = []
                            foolist = member.autoKickList
                            if bannedPlayerID not in foolist:
                                member_option.add_ban(client_id=bannedPlayerID)
                                bsInternal._chatMessage("玩家 "+str(bannedPlayerID) + " 已封禁！")
                                reload(member)
                            else:
                                bs.screenMessage("玩家 "+str(bannedPlayerID) + " 已经被封禁了！", color=(1,0,0), clients=[clientID], transient=True)
                                
            elif m == '#unban':
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage("请使用 玩家ID 来指定要解封的玩家！", color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        if len(a[0]) > 2:
                            for i in bs.getActivity().players:
                                try:
                                    if (i.getName()).encode('utf-8') == (a[0]):
                                        bannedClient = i.getInputDevice().getClientID()
                                        bannedName = i.getName().encode('utf-8')
                                        bannedPlayerID = i.get_account_id()
                                        foolist = []
                                        foolist = member.autoKickList
                                        if bannedPlayerID in foolist:
                                            member_option.del_ban(client_id=bannedPlayerID)
                                            bsInternal._chatMessage("玩家 " + str(bannedName) + " 已解封！")
                                            reload(member)
                                        else:
                                            bs.screenMessage("玩家 " + str(bannedName) + " 不在封禁名单中！", color=(1,0,0), clients=[clientID], transient=True)
                                except Exception:
                                    pass
                        else:
                            try: 
                                bannedClient = bsInternal._getForegroundHostSession().players[int(a[0])]
                            except Exception: 
                                bs.screenMessage("未发现此玩家", color=(1,0,0), clients=[clientID], transient=True)
                            else:
                                foolist = []
                                foolist = member.autoKickList
                                bannedPlayerID = bannedClient.get_account_id()
                                if bannedPlayerID in foolist:
                                    member_option.del_ban(client_id=bannedPlayerID)
                                    bsInternal._chatMessage("玩家 " + str(bannedClient) + " 已解封！")
                                    reload(member)
                                else:
                                    bs.screenMessage("玩家 " + str(bannedClient) + " 不在封禁名单中！", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#unbanid':
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage('请使用 设备ID 来指定要解封的玩家！', color=(1,0,0), clients=[clientID], transient=True)
                    else:               
                        if len(a[0]) > 2:
                            bannedPlayerID = str(a[0])
                            foolist = []
                            foolist = member.autoKickList
                            if bannedPlayerID in foolist:
                                member_option.del_ban(client_id=bannedPlayerID)
                                bsInternal._chatMessage("玩家 "+str(bannedPlayerID) + " 已解封！")
                                reload(member)
                            else:
                                bs.screenMessage("玩家 "+str(bannedPlayerID) + " 不在封禁列表中！", color=(1,0,0), clients=[clientID], transient=True)
                    
            elif m == '#amnesty':
                if self.check_owner(clientID=clientID):
                    foolist = []
                    bsInternal._chatMessage("==========正在清除封禁名单...==========")
                    with open(bs.getEnvironment()['systemScriptsDirectory'] + "/anm/member.py") as file:
                        s = [row for row in file]
                        s[1] = 'autoKickList = '+ str(foolist) + '\n'
                        f = open(bs.getEnvironment()['systemScriptsDirectory'] + "/anm/member.py",'w')
                        for i in s:
                            f.write(i)
                        f.close()
                        reload(member)
                    bsInternal._chatMessage("===============完成！===============")
                    
            elif m == '#maxplayers':
                if self.check_owner(clientID=clientID):
                    if a == []:
                        bs.screenMessage("请在命令后面加上最大派对人数！", color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        try:
                            bsInternal._getForegroundHostSession()._maxPlayers = int(a[0])
                            bsInternal._setPublicPartyMaxSize(int(a[0]))
                            bsInternal._chatMessage('现在服务器最大加入游戏人数为: ' + str(int(a[0])) + ' 人！')
                        except Exception:
                            bs.screenMessage("AN ERROR OCCURED", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#remove':
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage("请使用 玩家ID 指定玩家", color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        if len(a[0]) > 2:
                            for i in bs.getActivity().players:
                                try:
                                    if (i.getName()).encode('utf-8') == (a[0]):
                                        i.removeFromGame()
                                except Exception:
                                    pass
                        else:
                            try:
                                bs.getActivity().players[int(a[0])].removeFromGame()
                            except Exception:
                                bs.screenMessage("未发现此玩家", color=(1,0,0), clients=[clientID], transient=True)

            elif m == '#cleanlog':
                if self.check_owner(clientID=clientID):
                    try:
                        with open("/home/Server-Duel/Server/log.txt", "r+") as file:
                            file.truncate(0)
                        bs.screenMessage("日志文件清除完毕！", color=(0,1,0), clients=[clientID], transient=True)
                    except Exception as e:
                        bs.screenMessage("日志文件清除失败！", color=(1,0,0), clients=[clientID], transient=True)

            elif m == "#id":
                if self.check_admin(clientID=clientID):
                    if a == []:
                        bs.screenMessage("请使用 玩家ID 来指定获取的玩家设备ID！", color=(1,0,0), clients=[clientID], transient=True)
                    else:
                        if len(a[0]) > 2:
                            for i in bs.getActivity().players:
                                try:
                                    if (i.getName()).encode('utf-8') == (a[0]):
                                        Client = i.getInputDevice().getClientID()
                                        Name = i.getName().encode('utf-8')
                                        PlayerID = i.get_account_id()
                                        bsInternal._chatMessage("成功获取玩家 " + Name+ " 的设备ID")
                                        bsInternal._chatMessage("ID :" + PlayerID)
                                except Exception:
                                    bs.screenMessage("获取玩家设备ID错误！", color=(1,0,0), clients=[clientID], transient=True)
                        else:
                            try: 
                                Client = bsInternal._getForegroundHostSession().players[int(a[0])]
                            except Exception: 
                                bs.screenMessage("未发现此玩家", color=(1,0,0), clients=[clientID], transient=True)
                            else:
                                PlayerID = Client.get_account_id()
                                Name = Client.getName().encode('utf-8')
                                bsInternal._chatMessage("成功获取玩家 " + Name+ " 的设备ID")
                                bsInternal._chatMessage("ID :" + PlayerID)

            elif m == '#end':
                if self.check_admin(clientID=clientID):
                    try:
                        bsInternal._getForegroundHostActivity().endGame()
                        bsInternal._chatMessage('系统提示: 管理员结束了比赛！')
                    except Exception:
                        bs.screenMessage("错误报告: 结束比赛时出现了错误！", color=(1,0,0), clients=[clientID], transient=True)
            
            elif m == '#help':
                if self.getId(clientID) in self.owner_list or self.getId(clientID) in self.admin_list:
                    bsInternal._chatMessage("===========管理员可用命令=========")
                    bsInternal._chatMessage("> #kick 踢出玩家 | #ban 封禁玩家")
                    bsInternal._chatMessage("> #remove 移除玩家 | #end 结束比赛")
                    bsInternal._chatMessage("> #unban 玩家解除封禁 ")
                    bsInternal._chatMessage("> #banid 使用玩家ID封禁玩家 ")
                    bsInternal._chatMessage("> #unbanid 使用玩家ID解除封禁 ")
                    bsInternal._chatMessage("> #id 获取玩家设备ID")
                
                if self.getId(clientID) in self.owner_list:
                    bsInternal._chatMessage("===========服主可用命令===========")
                    bsInternal._chatMessage("> #amnesty 清除封禁列表 ")
                    bsInternal._chatMessage("> #maxplayers 设置服务器最大人数")
                    bsInternal._chatMessage("> #cleanlog 清除日志文件")
                    bsInternal._chatMessage("> #admin / #adminid 添加管理员")
                    bsInternal._chatMessage("> #unadmin / #unadminid 删除管理员")

            else:
                bs.screenMessage('抱歉！没有此管理命令！', clients = [clientID], transient=True, color=(1, 0, 0))
                                
        
c = chatOptions()

def cmd(msg, clientID):
    if bsInternal._getForegroundHostActivity() is not None:
        c.opt(clientID, msg)
